package es.uam.eps.maprednat;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;

public class MembraneJoin implements WritableComparable<MembraneJoin> {
	private static String SEPARATOR = ":";
	private static String NULL = "_";
	
	private String label = null;
	private String struct = null;
	private String symbols = null;
	private String delete = null;
	
	public MembraneJoin()
	{
		
	}
	
	public MembraneJoin(String label, String struct, String symbols, String delete)
	{
		this.label = label;
		this.struct = struct;
		this.symbols = symbols;
		this.delete = delete;
	}
	
	public MembraneJoin(MembraneJoin other)
	{
		this.label = other.label;
		this.struct = other.struct;
		this.symbols = other.symbols;
		this.delete = other.delete;
	}
	
	public void join(MembraneJoin m){
		if (label==null && m.label!=null ) this.label = m.label;
		if (struct==null && m.struct!=null ) this.struct = m.struct;
		if (m.symbols!=null){
			if (symbols==null) 
				this.symbols = m.symbols;
			else
				this.symbols = symbols + "," + m.symbols;
		}
		if (delete==null && m.delete!=null ) this.delete = m.delete;

		if (struct!=null && delete!=null){
			this.struct = this.struct.replace(delete, "");
			this.delete = null;
		}
	}
	
	
	public String toString()
	{
		String res = (label==null?NULL:label)+SEPARATOR+(struct==null?NULL:struct);
		if (symbols!=null) res+=SEPARATOR+symbols;
		return res;
	}
	
	public void write(DataOutput out) throws IOException {
		String serialize = (label==null?NULL:label)+SEPARATOR+(struct==null?NULL:struct)+SEPARATOR+(symbols==null?NULL:symbols)+SEPARATOR+(delete==null?NULL:delete);
	    new Text(serialize).write(out);
	}
       
	public void readFields(DataInput in) throws IOException{
		Text t = new Text();
		t.readFields(in);
		String parts[] = t.toString().split(SEPARATOR);
		this.label = (parts[0].equals(NULL)?null:parts[0]);
		this.struct = (parts[1].equals(NULL)?null:parts[1]);
		this.symbols = (parts[2].equals(NULL)?null:parts[2]);
		this.delete = (parts[3].equals(NULL)?null:parts[3]);
	}

	public int compareTo(MembraneJoin other) {
		return this.toString().compareTo(other.toString());
	}
}
